<template>
  <div class="rule-manage">
    <el-form label-width="120px" label-position="top">
      <el-row :gutter="40" class="rule-manage-form">
        <el-col :span="6">
          <el-form-item :label="$t('report.quaRuleName1')">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('report.quaRuleType1')">
            <el-select v-model="form.type">
              <el-option :label="$t('public.pleasePick')" value=""></el-option>
              <el-option :label="$t('report.quaCallQuality')" value="call"></el-option>
              <el-option :label="$t('report.quaWebchatQuality')" value="webchat"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('intelligentQualityCheck.intelCorrelation')">
            <el-select v-model="scoreForSearch">
              <el-option :label="$t('public.pleasePick')" value=""></el-option>
              <el-option v-for="item in scoreConfig" :label="item.name" :value="item._id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('monitor.updateAgent')">
            <el-popover
              ref="agentPop"
              placement="bottom"
              @show="popoverShow"
              width="240"
              trigger="click">
              <agent-tree :readSeat="folllowedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
            </el-popover>
            <div class="follow-agent-wrap" v-popover:agentPop>
                        <span class="follow-agent follow-common" v-for="item in folllowedAgents" :key="item._id">{{item.label}}
                          <i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)"></i>
                        </span>
              <div>
                <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="sub">
      <el-button type="primary" class="primary_btn fr ml10" @click="searchRuleList">{{$t('public.search2')}}</el-button>
      <el-button class="primary_btn fr" style="margin-right: 20px;" @click="resetCondition">{{$t('public.reset')}}</el-button>
    </div>
    <affix :label="$t('public.searchResult')" style="margin-top:28px;padding-bottom:0;"></affix>
    <el-button type="primary" class="primary_btn fr ml10" style="margin-bottom:20px;" @click="addRuleManageBtn">{{$t('configLazyLoad.intelligentQualityCheck.addRule')}}</el-button>
    <div style="clear: both;"></div>
    <div class="deploy">
      <div class="fl deploySelect">
        <el-select v-model="isEnable" size="mini" :placeholder="$t('configLazyLoad.intelligentQualityCheck.chooseType')" @change="changeEnable">
           <el-option :label="$t('configLazyLoad.intelligentQualityCheck.lookEnableRule')" value="true"></el-option>
            <el-option :label="$t('configLazyLoad.intelligentQualityCheck.lookAllRule')" value="false"></el-option>
          </el-select>
      </div>
      <Pagination
        class="fr"
        :small="true"
        :currentPage="currentPage"
        :count="count"
        @turnPage="searchRuleListTurnPage"
        :totalPage="Math.ceil(count/10)"
      >
      </Pagination>
    </div>
    <!--表格===============================================-->
    <el-table :data="ruleList" stripe size="mini">
      <el-table-column prop="name" :label="$t('report.quaRuleName1')">
      </el-table-column>
      <el-table-column prop="type_show" :label="$t('report.quaRuleType1')">
      </el-table-column>
      <el-table-column prop="note" :label="$t('sms.introduce')" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="scoreConfig_show" :label="$t('intelligentQualityCheck.intelCorrelation')">
      </el-table-column>
      <el-table-column prop="updateUser_show" :label="$t('monitor.updateAgent')">
      </el-table-column>
      <el-table-column prop="updateTime" :label="$t('configLazyLoad.intelligentQualityCheck.updateTime')">
      </el-table-column>
      <el-table-column  :label="$t('sms.operate')" width="150">
        <template scope="scope">
          <el-button v-if="ruleList[scope.$index].isEnable" type="text" @click.stop="enOrDisableRule(scope.$index, ruleList, false)" size="small">{{$t('sms.stop')}}</el-button>
          <el-button v-if="!ruleList[scope.$index].isEnable" type="text" @click.stop="enOrDisableRule(scope.$index, ruleList, true)" size="small">{{$t('sms.reuse')}}</el-button>
          <el-button type="text" size="small" @click="editRuleManageBtn(scope.$index, ruleList)">{{$t('public.edit2')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import Pagination from '@/components/public-modules/card/Pagination'
  import {deepClone} from '@/utils/m7Utils.js'
  import Affix from '../../../../ui-modules/affix/Affix.vue'
  import AgentTree from '../../../qualityCheck/base/qualityAgentTree.vue'
  import bus from '@/store/eventBus'
  import * as types from '@modules/config/intelligent-quality-check-config/mutation-types.js'
  export default {
    name: 'RuleManage',
    data () {
      return {
        form: {     //   查询条件
          name: '',
          type: '',
          user: [],
          scoreConfig: {},
          isEnable:true
        },
        scoreConfig: [],      //   搜索条件  关联计分项  option用的数据
        scoreForSearch: '',   //   搜索条件  关联计分项  model
        DISPOSAL_AGENT: [],   //   修改人条件 相关
        ruleList: [],         //   table渲染用
        count: 10,
        currentPage: 1,
        isEnable:'true'
      }
    },
    methods: {
      addRuleManageBtn () {
        this.$store.commit(types.MARK_RULE_DETAIL, null)
        this.$router.push({path: '/index/config/intelligentQualityCheckConfig/ruleManageDetail'})
        bus.$emit('markRuleInfo')
      },
      editRuleManageBtn (index, data) {
        let _id = data[index]._id
        this.$store.dispatch('getRuleDetailConfig', {_id: _id}).then(res => {
          if (res.success) {
            this.$store.commit(types.MARK_RULE_DETAIL, res.data)
            this.$router.push({path: '/index/config/intelligentQualityCheckConfig/ruleManageDetail'})
            bus.$emit('markRuleInfo')
          }
        })
      },
      resetCondition () {
        this.form.name = ''
        this.form.type = ''
        this.DISPOSAL_AGENT = []
        this.$refs.agentTree.setCheckedKeys()
        this.scoreForSearch = ''
      },
      searchRuleListTurnPage (val) {
        this.currentPage = val
        this.form.page = val
        this.search()
      },
      searchRuleList () {
        this.form.page = 1
        this.currentPage = 1
        this.search()
      },
      search () {
        this.form.pageSize = 10
        this.form.user = this.DISPOSAL_AGENT
        this.form.scoreConfig.parent = this.scoreForSearch.split('##')[0]
        this.form.scoreConfig.sub = this.scoreForSearch.split('##')[1]
        this.$store.dispatch('getMarkRuleListConfig', this.form).then(res => {
          if (res.success) {
            this.ruleList = res.data
            let agents = this.$store.getters.agents
            this.ruleList.forEach(item => {
              if (item.type === 'call') {
                item.type_show = this.$t('report.quaCallQuality')
              } else {
                item.type_show = this.$t('report.quaWebchatQuality')
              }
              if (agents[item.updateUser]) {
                item.updateUser_show = agents[item.updateUser].displayName
              } else {
                item.updateUser_show = ''
              }
              item.scoreConfig_show = item.scoreConfig.sub.name ? item.scoreConfig.parent.name + '-' + item.scoreConfig.sub.name : this.$t('configLazyLoad.intelligentQualityCheck.ruleError2')
            })
            this.count = res.count
          }
        })
      },
      enOrDisableRule (index, data, val) {
        let dataObj = {}
        dataObj._id = data[index]._id
        dataObj.flag = val
        this.$store.dispatch('enOrDisableRuleConfig', dataObj).then(res => {
          if (res.success) {
            if (dataObj.flag) {
              this.$message.success(this.$t('sms.reuseSuccess'))
              // this.ruleList[index].isEnable = true
            } else {
              this.$message.success(this.$t('sms.stopSuccess'))
              // this.ruleList[index].isEnable = false
            }
            this.searchRuleList()
          } else {
            if (dataObj.flag && res.message === 'scoreConfig_has_ben_removed') {
              this.$message.error(this.$t('configLazyLoad.intelligentQualityCheck.ruleError1'))
            }
          }
        })
      },
//      修改人搜索条件  相关===
      saveFollowedAgents (agents) {
        this.DISPOSAL_AGENT = deepClone(agents)
        document.getElementsByTagName('body')[0].click()
      },
      closeFollowedAgents (agent) {
        this.DISPOSAL_AGENT = this.DISPOSAL_AGENT.filter((item) => item !== agent)
      },
      popoverShow () {
        this.$refs.agentTree.setCheckedKeys()
      },
      changeEnable(val){
        this.isEnable = val;
        this.form.isEnable = val;
        if(this.isEnable=='false'){
          delete this.form.isEnable 
        }else{
          this.form.isEnable = true;
        }
        this.searchRuleList()
      }
    },
    computed: {
      folllowedAgents () {
        let agents = this.DISPOSAL_AGENT || []
        let agentsAll = this.$store.getters.agents || {}
        return agents.map((item) => {
          return {_id: item, label: agentsAll[item].displayName}
        })
      }
    },
    components: {
      Affix,
      AgentTree,
      Pagination
    },
    beforeMount () {
      this.$store.dispatch('getScoreConfig', {}).then(res => {
        console.log(res,'res')
        if (res.success) {
          if (res.data) {
            let data = res.data
            this.scoreConfig = []
            let scoreItem = {}
            data.forEach(item => {
              item.subs.forEach(one => {
                scoreItem = {}
                scoreItem.name = item.name + '-' + one.name
                scoreItem._id = one.parent + '##' + one._id
                this.scoreConfig.push(scoreItem)
              })
            })
          }
        }
      })
      this.searchRuleList()
    },
    activated () {
      this.searchRuleList()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .rule-manage
    padding 20px
    height calc(100vh - 125px)
    width calc(100%)
    overflow-y auto
    overflow-x hidden
    box-sizing border-box
    .rule-manage-form
      .el-input,.el-select
        width 100%
    .sub
      overflow hidden
      margin 20px 0
    .follow-label
      line-height 24px
      font-size 12px
    .follow-agent-wrap
      display inline-block
      cursor pointer
      width: 220px
      border-radius: 5px
      border: 1px solid #dcdfe6
      padding: 6px 9px 6px 5px
      margin-top 7px
      overflow: hidden
    .follow-common
      float left
      position relative
      line-height 24px
      background-color #7ab8f3
      margin 0 0 10px 10px
      padding 0 10px
      color #fff
      border-radius 4px
    .follow-agent-add
      cursor pointer
    .el-icon-close
      font-size 12px
    .follow-agent
      &:hover
        .el-icon-close
          display block
      .el-icon-close
        display none
        position absolute
        right -10px
        top -10px
        width 24px
        height 24px
        font-size 12px
        line-height 24px
        transform scale(0.6)
        text-align center
        color #fff
        background-color #0f99fc
        border-radius 50%
        border 1px solid #cce6ff
        cursor pointer
    .follow-agent-wrap-btn
      display block !important
      line-height 0px
      float right
      cursor pointer
      color $c-main
      overflow: hidden
    .deploy
      height 48px
      border 1px solid #e7e7eb
      border-bottom none
      padding-left 14px
      .deploySelect
          margin-top 10px
      .table-header-config
        float left
        line-height 42px
      .iconfont
        font-size 18px
        color $c-main
        float left
      .tex
        cursor pointer
        margin-left 10px
      .page
        margin-top 10px
      .el-pagination
        padding 0
</style>
